import uuid
import os
import requests


def download_file(url, save_dir):
    # Generate a unique filename using UUID
    filename = str(uuid.uuid4()) + '.jpg'  # Assuming the file is a JPG image

    # Construct the full path to save the file
    filepath = os.path.join(save_dir, filename)

    # Ensure the directory exists
    os.makedirs(save_dir, exist_ok=True)  # Create the directory if it does not exist

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
        'Accept-Encoding': 'gzip, deflate, br, zstd',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Cache-Control': 'max-age=0',
        'Referer': 'https://www.elysium.pro/Photobooks/Album/720?pageNumber=5',
        'Sec-Ch-Ua': '"Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"',
        'Sec-Ch-Ua-Mobile': '?0',
        'Sec-Ch-Ua-Platform': '"Windows"',
        'Sec-Fetch-Dest': 'document',
        'Sec-Fetch-Mode': 'navigate',
        'Sec-Fetch-Site': 'same-origin',
        'Sec-Fetch-User': '?1',
        'Upgrade-Insecure-Requests': '1',
        # If necessary, add Cookie
        'Cookie': 'ARRAffinity=5337f9faa36f86559a728fdbcc126a6ba2cd3716ba5bc4131378e2b44b836b4a; ARRAffinitySameSite=5337f9faa36f86559a728fdbcc126a6ba2cd3716ba5bc4131378e2b44b836b4a; .AspNetCore.Antiforgery.cdV5uW_Ejgc=CfDJ8ExtWuUNqIZIpK46MLABsgXNj1v3A72OM87OEjolrx2FiagIjGHShslRkvVuL-ybaTSve3N5FFrCH2DzQ1QnRjC72Clo-pyHToLU3aVUiROKnE-FVDsND9O2T8NWv8TH9hA1fKgFk_A535TfmlfjhnE',
    }

    # Make the request
    response = requests.get(url, headers=headers)

    # Check if the request was successful
    if response.status_code == 200:
        # Write the file
        with open(filepath, 'wb') as file:
            for chunk in response.iter_content(chunk_size=1024):
                if chunk:
                    file.write(chunk)
    else:
        print(f"Failed to download the file. Status code: {response.status_code}")


# Read URLs from the text file and download them
save_directory = r'E:\picture'  # Note the double backslashes or use forward slashes ('/')
with open('url.txt', 'r', encoding='utf-8') as file:
    for line in file:
        url = line.strip()  # Remove any trailing newline characters
        download_file(url, save_directory)